<script setup>
import { useUserStore } from '@/stores'
import { ref } from 'vue'
import {
  addProblemAPI,
  getTagAPI,
  getTodayInfoAPI,
  getNewAnswerAPI,
  getNewProblemAPI,
  getTotalAnswerAPI,
  getTotalUserAPI,
  getTotalProblemAPI,
  getUserProblemAPI,
  settleProblemAPI,
  getAnswerCountAPI
} from '@/api/user'

import { useRouter } from 'vue-router'
import { onMounted, watch } from 'vue'

const userStore = useUserStore()
const router = useRouter()
import * as echarts from 'echarts'
import { onBeforeMount } from 'vue'

const handleCommand = (command) => {
  if (command === 'LoginOut') {
    userStore.removeUserInfo()
    userStore.removeToken()
    ElMessage('退出成功')
    router.push('/')
  } else {
    router.push('/home/user/UserDetail')
  }
}

const rewardLevel = ref('') // 新增悬赏阶级响应式变量

// 悬赏阶级选项
const rewardOptions = [
  { value: '0', label: '无悬赏' },
  { value: '1-5', label: '简单' },
  { value: '6-20', label: '中等' },
  { value: '20+', label: '困难' }
]

// 根据悬赏阶级限制输入金额的函数
const limitMoneyInput = (level) => {
  switch (level) {
    case '0':
      addedQuestion.value.Money = '' // 无悬赏时清空输入
      break
    case '1-5':
      if (addedQuestion.value.Money < 1 || addedQuestion.value.Money > 5) {
        ElMessage.error('请输入1-5之间的数字')
        addedQuestion.value.Money = '' // 清空非法输入
      }
      break
    case '6-20':
      if (addedQuestion.value.Money < 6 || addedQuestion.value.Money > 20) {
        ElMessage.error('请输入6-20之间的数字')
        addedQuestion.value.Money = '' // 清空非法输入
      }
      break
    case '20+':
      if (addedQuestion.value.Money < 20) {
        ElMessage.error('请输入20及以上的数字')
        addedQuestion.value.Money = '' // 清空非法输入
      }
      break
  }
}

const showAdd = ref(false)
const addedQuestion = ref({})
const showAddQuestion = () => {
  showAdd.value = true
  addedQuestion.value = {}
}

const loading = ref(false)

const getAnswerCount = async (ProblemId) => {
  const res = await getAnswerCountAPI({ ProblemId })
  console.log(res.data)
  let a = String(res.data)
  return a
}

const addProblem = async () => {
  // 验证问题内容和标签是否已填写
  if (!addedQuestion.value.ProblemName) {
    ElMessage.error('请填写问题内容')
    return
  }
  if (!addedQuestion.value.Tag) {
    ElMessage.error('请选择标签')
    return
  }

  limitMoneyInput(rewardLevel.value)
  // 检查悬赏金额是否为空
  if (
    addedQuestion.value.Money === undefined ||
    addedQuestion.value.Money === ''
  ) {
    ElMessage.error('请填写悬赏金额')
    return
  }

  const rewardAmount = Number(addedQuestion.value.Money)
  if (rewardAmount < 0) {
    ElMessage.error('悬赏金额不能为负数')
    return
  } else if (rewardAmount === 0) {
    ElMessage.warning('悬赏金额为0，将被视为非悬赏问题')
    // 你可以选择在这里继续或返回，视你的逻辑而定
  }

  // 继续后续代码

  loading.value = true
  try {
    const res = await addProblemAPI({
      ...addedQuestion.value,
      Status: 1,
      UserName: userStore.userInfo.userName
    })
    if (res.data === 1) {
      showAdd.value = false
      ElMessage.success('问题发布成功')
    } else {
      ElMessage.error('余额不足')
    }
  } catch (error) {
    ElMessage.error('出现错误，请重试')
  } finally {
    loading.value = false
    const now = new Date()
    const diff = dateTime.value - now.getTime()

    setTimeout(async () => {
      console.log('时间已到！执行定时任务')

      try {
        const res = await getUserProblemAPI({
          UserName: userStore.userInfo.userName
        })
        console.log(res.data)

        for (let i = 0; i < res.data.length; i++) {
          res.data[i].account = await getAnswerCount(res.data[i].Id)
          if (res.data[i].status != 0 && res.data[i].account != 0&&res.data[i].status != 2) {
            await settleProblemAPI({ Id: res.data[i].Id })
          }
        }
      } catch (error) {
        console.error('发生错误:', error)
      }
    }, diff)
  }
}

const Tags = ref([])
const getTag = async () => {
  const res = await getTagAPI()
  Tags.value = res.data
}

const filterByTag = ref('')

//今日登录
const todayLoginInfo = ref(0)
const getTodayLoginInfo = async () => {
  const res = await getTodayInfoAPI()
  todayLoginInfo.value = res.data
}
//今日回答
const todayAnswerInfo = ref(0)
const getTodayAnswerInfo = async () => {
  const res = await getNewAnswerAPI()
  todayAnswerInfo.value = res.data
}
//今日问题
const todayQuestionInfo = ref(0)
const getTodayQuestionInfo = async () => {
  const res = await getNewProblemAPI()
  todayQuestionInfo.value = res.data
}
//总用户
const totalUserInfo = ref(0)
const getTotalUserInfo = async () => {
  const res = await getTotalUserAPI()
  totalUserInfo.value = res.data
}
//总回答
const totalAnswerInfo = ref(0)
const getTotalAnswerInfo = async () => {
  const res = await getTotalAnswerAPI()
  totalAnswerInfo.value = res.data
}
//总问题
const totalQuestionInfo = ref(0)
const getTotalQuestionInfo = async () => {
  const res = await getTotalProblemAPI()
  totalQuestionInfo.value = res.data
}
const maxToday = () => {
  return (
    Math.max(
      todayLoginInfo.value,
      todayQuestionInfo.value,
      todayAnswerInfo.value
    ) +
    Math.floor(
      Math.max(
        todayLoginInfo.value,
        todayQuestionInfo.value,
        todayAnswerInfo.value
      ) / 10
    )
  )
}
const maxTotal = () => {
  return (
    Math.max(
      totalUserInfo.value,
      totalQuestionInfo.value,
      totalAnswerInfo.value
    ) +
    Math.floor(
      Math.max(
        totalUserInfo.value,
        totalQuestionInfo.value,
        totalAnswerInfo.value
      ) / 10
    )
  )
}

const dateTime = ref()
const handTime = (param) => {
  const date = new Date(param)

  const padZero = (num) => String(num).padStart(2, '0')
  const formattedDate = `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}:${padZero(date.getSeconds())}`

  addedQuestion.value.time = formattedDate // 2024-11-25 23:18:11
  dateTime.value = date.getTime()
}

watch(
  () => addedQuestion.value.Money,
  () => {
    setTimeout(() => {
      limitMoneyInput(rewardLevel.value)
    }, 800)
  }
)

onBeforeMount(() => {
  getTag()
  Promise.all([
    getTodayLoginInfo(),
    getTodayAnswerInfo(),
    getTodayQuestionInfo(),
    getTotalUserInfo(),
    getTotalAnswerInfo(),
    getTotalQuestionInfo()
  ])
})
onMounted(() => {
  const chartDom = document.getElementById('today')
  const myChart = echarts.init(chartDom)
  let option

  const updateTodayChart = () => {
    option = {
      title: [{ text: '今日信息' }],
      polar: { radius: [30, '80%'] },
      radiusAxis: { max: maxToday() },
      angleAxis: {
        type: 'category',
        data: ['登录人数', '新增问题', '新增回答'],
        startAngle: 75
      },
      tooltip: {},
      series: {
        type: 'bar',
        data: [
          todayLoginInfo.value,
          todayQuestionInfo.value,
          todayAnswerInfo.value
        ],
        coordinateSystem: 'polar',
        label: { show: true, position: 'middle', formatter: '{b}: {c}' }
      },
      animation: false
    }
    myChart.setOption(option)
  }

  const chartDom2 = document.getElementById('total')
  const myChart2 = echarts.init(chartDom2)
  let option2

  const updateTotalChart = () => {
    option2 = {
      title: [{ text: '平台信息' }],
      polar: { radius: [30, '80%'] },
      angleAxis: { max: maxTotal(), startAngle: 75 },
      radiusAxis: {
        type: 'category',
        data: ['平台用户数', '总问题数', '总回答数']
      },
      tooltip: {},
      series: {
        type: 'bar',
        data: [
          totalUserInfo.value,
          totalQuestionInfo.value,
          totalAnswerInfo.value
        ],
        coordinateSystem: 'polar',
        label: { show: true, position: 'middle', formatter: '{b}: {c}' }
      }
    }
    myChart2.setOption(option2)
  }

  // 初始化图表
  updateTodayChart()
  updateTotalChart()

  // 监听数据变化并更新图表
  watch([todayLoginInfo, todayQuestionInfo, todayAnswerInfo], updateTodayChart)
  watch([totalUserInfo, totalQuestionInfo, totalAnswerInfo], updateTotalChart)
})

const searchByTag = (tag) => {
  filterByTag.value = tag
}
</script>

<template>
  <div class="common-layout">
    <el-container class="banner">
      <el-header class="header">
        <el-menu default-active="route.path" class="el-menu-demo" mode="horizontal" @select="handleSelect" router>
          <span class="logo-text">付费问答系统</span>
          <el-menu-item index="/home/user/index" class="indexTitle">首页</el-menu-item>
          <el-menu-item index="/home/user/MyQuestion" class="indexTitle">我的问题</el-menu-item>
          <el-menu-item index="/home/user/MyAnswer" class="indexTitle">我的回答</el-menu-item>
          <el-menu-item index="/home/user/MyCollect" class="indexTitle">我的收藏</el-menu-item>
          <el-sub-menu index="2" class="indexTitle">
            <template #title>
              <span class="indexTitle">我的举报</span>
            </template>
            <el-menu-item index="/home/user/MyReportQuestion">问题举报</el-menu-item>
            <el-menu-item index="/home/user/MyReportAnswer">回答举报</el-menu-item>
          </el-sub-menu>
          <el-menu-item index="/home/user/Aipage" class="indexTitle">AI助手</el-menu-item>
          <el-button type="primary" plain round class="do-question" @click="showAddQuestion()">
            我要提问
          </el-button>
          <span class="user-info" style="cursor: pointer">
            欢迎你，
            <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link">{{
                userStore.userInfo.userName
              }}</span>
              <template v-slot:dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="UserDetail">个人中心</el-dropdown-item>
                  <el-dropdown-item command="LoginOut">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </span>
        </el-menu>
      </el-header>
      <el-container>
        <el-main class="main">
          <div class="after"></div>
          <div class="sidebar">
            <h2>大家都在搜</h2>
            <el-menu>
              <el-menu-item v-for="tag in Tags" :key="tag.TagName" @click="searchByTag(tag.TagName)">
                {{ tag.TagName }}
              </el-menu-item>
            </el-menu>
          </div>
          <div class="content">
            <router-view :filter="filterByTag"></router-view>
          </div>
        </el-main>
        <!-- 侧边可视化信息 -->
        <el-aside class="Aside">
          <div>
            <div id="today" style="width: 250px; height: 300px"></div>
            <div id="total" style="width: 250px; height: 300px"></div>
          </div>
        </el-aside>
      </el-container>
    </el-container>

    <el-dialog v-model="showAdd" title="发布问题" width="500">
      <el-form :model="addedQuestion">
        <el-form-item label="问题:" required>
          <el-input v-model="addedQuestion.ProblemName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="标签:" required>
          <el-select v-model="addedQuestion.Tag" placeholder="选择标签" size="large">
            <el-option v-for="item in Tags" :key="item.TagName" :label="item.TagName" :value="item.TagName" />
          </el-select>
        </el-form-item>
        <el-form-item label="悬赏阶级:" required>
          <el-select v-model="rewardLevel" placeholder="选择悬赏阶级" size="large" @change="limitMoneyInput">
            <el-option v-for="item in rewardOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="问题悬赏:" required>
          <el-input v-model="addedQuestion.Money" autocomplete="off" />
        </el-form-item>
        <el-form-item label="截止时间" prop="deadline">
          <el-date-picker v-model="addedQuestion.deadline" type="datetime" placeholder="选择截止时间"
            :disabled-date="disabledDate" @change="handTime" />
        </el-form-item>
        <div class="form-footer">
          <el-button type="primary" @click="addProblem()" :loading="loading">发 布</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<style scoped>
.Aside {
  width: 250px;
  background-color: #fff;
  border-radius: 10px;
  margin: 20px 10px;
}

* {
  margin: 0;
  padding: 0;
}

.header {
  width: 100%;
  position: sticky;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  top: 0;
  background: #fff;
  z-index: 1000;
}

.el-menu-demo {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.indexTitle {
  font-size: 18px;
  font-weight: 600;
  transition: color 0.3s;
}

.indexTitle:hover {
  color: #3670ee;
  /* 悬停变色 */
}

.logo-text {
  font-size: 36px;
  color: #3670ee;
  font-weight: bold;
  margin: 0 20px;
}

.do-question {
  margin-left: 20px;
}

.user-info {
  font-size: 14px;
  font-weight: 600;
  display: flex;
  align-items: center;
}

.common-layout {
  background-color: #f9f9f9;
  min-height: 100vh;
  /* 确保布局至少有全屏高度 */
  display: flex;
}

.after {
  height: 10px;
}

.main {
  display: flex;
  /* 使用 Flexbox 布局 */
  width: 1000px;
  margin: 20px auto;
  background-color: #ffffff;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 20px;
  overflow-y: auto;
  /* 允许问题区域有滚动条 */
  scrollbar-width: none;
  max-height: calc(100vh - 100px);
  /* 根据需要调整高度 */
}

.sidebar {
  width: 150px;
  /* 侧边栏宽度 */
  padding: 20px;
  border-right: 1px solid #eaeaea;
  /* 右边框 */
  background-color: #ffffff;
  /* 背景色 */
  border-radius: 10px;
  /* 圆角 */
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  /* 阴影效果 */
}

.sidebar h2 {
  font-size: 20px;
  margin-bottom: 15px;
  color: #3670ee;
  /* 标题颜色 */
}

.el-menu-item {
  padding: 10px 15px;
  /* 增加内边距 */
  transition:
    background 0.3s,
    color 0.3s;
  /* 动画效果 */
}

.el-menu-item:hover {
  background-color: #f0f8ff;
  /* 悬停背景色 */
  color: #3670ee;
  /* 悬停文字颜色 */
}

.el-menu-item:active {
  background-color: #e6f7ff;
  /* 点击时背景色 */
}

.content {
  flex: 1;
  /* 主内容区域自适应 */
  padding: 20px;
}

/* 隐藏页面右侧滚动条 */
html {
  overflow-y: hidden;
}
</style>
